<template>
  <div ref="gallery" class="image-gallery">
    <!-- 工具栏 -->
    <div class="toolbar">
      <!-- 左侧部分 -->
      <div class="left-section">
        <!-- 导入按钮 -->
        <el-button type="primary" @click="importImages">导入</el-button>
        <!-- 全选按钮 -->
        <el-button type="primary" @click="selectAll">{{ isAllSelected ? '取消全选' : '全选' }}</el-button>
        <!-- 删除所选项按钮 -->
        <el-button type="danger" @click="deleteDialog(null)">删除所选项</el-button>
        <!-- 下载所选项按钮 -->
        <!--        <el-button type="primary" @click="downloadSelected">下载所选项</el-button>-->
      </div>
      <!-- 右侧部分 -->
      <!--      <div class="right-section">-->
      <!--        &lt;!&ndash; 搜索按钮 &ndash;&gt;-->
      <!--        <el-button type="primary" @click="searchImages">搜索</el-button>-->
      <!--        &lt;!&ndash; 搜索输入框 &ndash;&gt;-->
      <!--        <el-input v-model="searchInput" placeholder="请输入搜索关键字"></el-input>-->
      <!--      </div>-->
    </div>
    <!-- 图片卡容器 -->
    <div class="image-card-container">
      <!-- 图片卡 -->
      <div
          v-for="(image, index) in images"
          :key="index"
          :style="{ width: cardWidth + 'px', height: cardHeight + 'px', marginRight: '10px', marginBottom: '10px', backgroundColor: isSelected(image) ? 'lightgray' : 'transparent' }"
          class="image-card"
          @click="selectImage(image)"
      >
        <div class="image-wrapper">
          <div class="color-block">
            <!-- 图片 -->
            <img :src="image.fileName" class="image"/>
          </div>
        </div>
        <!-- 按钮区域 -->
        <div class="buttons">
          <!-- 下载按钮 -->
          <!--          <el-button class="action-button" type="primary" @click="downloadImage(image)">-->
          <!--            <el-icon>-->
          <!--              <Download/>-->
          <!--            </el-icon>-->
          <!--          </el-button>-->
          <!-- 查看详情按钮 -->
          <el-button class="action-button" type="info" @click="viewDetails(image)">
            <el-icon>
              <Warning/>
            </el-icon>
          </el-button>
          <!-- 删除按钮 -->
          <el-button class="action-button" type="danger" @click="deleteDialog(image)">
            <el-icon>
              <DeleteFilled/>
            </el-icon>
          </el-button>
        </div>
      </div>
    </div>
    <!-- 分页块 -->
    <div class="pagination-block">
      <!-- 分页组件 -->
      <el-pagination
          small
          :pager-count="5"
          v-model:page-size="pageSize"
          :page-sizes="[8, 16, 32, 64]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <el-dialog
      v-model="uploadVisible"
      :modal="true"
      :show-arrow="true"
      :width="800"
      :show-close="false"
      content="this is content, this is content, this is content"
  >
    <el-upload
        :headers="this.headerObject"
        :action="serverIp() + '/api/related_photo/uploadSign'"
        class="upload-demo"
        drag
        multiple
    >
      <el-icon class="el-icon--upload">
        <upload-filled/>
      </el-icon>
      <div class="el-upload__text">
        拖拽上传或者 <em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          jpg/png文件应小于 5MB
        </div>
      </template>
    </el-upload>
    <div style="text-align: center">
      <el-button @click="getData()">确定</el-button>
    </div>
  </el-dialog>
  <el-image-viewer v-if="imgViewerVisible" :onClose="closeViewer" :url-list="this.urlList"/>
</template>

<script>
import request from "../../util/request.js";
import {DeleteFilled, Download, UploadFilled, Warning} from '@element-plus/icons-vue'
import {serverIp} from "../../../public/static/config.js";
import {downloadFile} from "@/util/photoDownload.js";

export default {
  components: {DeleteFilled, Download, Warning, UploadFilled},
  data() {
    return {
      headerObject:{
        "account" : JSON.parse(localStorage.getItem('user')).accountNo,
        "token" : JSON.parse(localStorage.getItem('user')).token
      },
      // 上传弹窗
      uploadVisible: false,
      // 查看详情
      urlList: [],
      imgViewerVisible: false, // 查看照片
      // 分页信息
      pageNum: 1,
      pageSize: 8,
      total: "",
      // 图片数据
      images: [],
      // 已选图片
      selectedImages: [],
      // 搜索输入
      searchInput: '',
      // 图片卡宽高
      cardWidth: 300,
      cardHeight: 330,
      // 图片卡间距
      baseMargin: 10,
      containerWidth: 0,
      cardMarginRight: 0,
      cardMarginBottom: 0
    };
  },
  computed: {
    // 是否全部选中
    isAllSelected() {
      return this.selectedImages.length === this.images.length;
    }
  },
  mounted() {
    // 获取容器宽度
    this.containerWidth = this.$refs.gallery.offsetWidth;
    // 获取所有图片数据
    this.getAllImageByPage();
    // 调整图片卡尺寸
    this.adjustCardSize();
    // 监听窗口大小变化
    window.addEventListener('resize', this.adjustCardSize);
  },
  beforeUnmount() {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.adjustCardSize);
  },
  methods: {
    getData() {
      this.uploadVisible = false
      request.get("/related_photo/updatePhotoWall").then(() => {
          location.reload()
      })
    },
    serverIp() {
      return serverIp
    },
    // 调整图片卡尺寸
    adjustCardSize() {
      const containerWidth = this.containerWidth;
      const numCardsPerRow = Math.floor(containerWidth / this.cardWidth);
      const totalMarginWidth = containerWidth - (numCardsPerRow * this.cardWidth);
      const adjustedCardMargin = totalMarginWidth / (numCardsPerRow - 1);

      this.cardMarginRight = Math.max(this.baseMargin, adjustedCardMargin);
      this.cardMarginBottom = Math.max(this.baseMargin, this.baseMargin * 2);
    },
    // 获取当前页图片数据
    getAllImageByPage() {
      request.get("/related_photo/findPage?pageNum=" + this.pageNum + "&pageSize=" + this.pageSize).then(res => {
        for (let key in res.data.data) {
          if (key === "records") {
            this.images = res.data.data[key];
          } else if (key === "total") {
            this.total = res.data.data[key];
          }
        }
      })
    },
    // 改变每页显示数量
    handleSizeChange(val) {
      this.pageSize = val;
      this.getAllImageByPage();
    },
    // 改变当前页码
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getAllImageByPage();
    },
    // 下载图片
    downloadImage(image) {
      // 下载逻辑
    },
    // 查看详情
    viewDetails(image) {
      // 查看详情逻辑
      this.urlList.push(image.fileName)
      this.imgViewerVisible = true
    },
    // 查看详情关闭
    closeViewer() {
      if (this.imgViewerVisible) {
        this.imgViewerVisible = false
        this.urlList.pop();
      }
    },
    // 确定删除弹窗
    deleteDialog(image) {
      this.$messageBox({
        title: '确定删除',
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        if (image === null) {
          this.deleteSelected()
          return
        }
        this.deleteImage(image);
      });
    },
    // 删除图片
    deleteImage(image) {
      // 删除逻辑
      this.selectedImages.pop();
      this.selectedImages.push(image)
      request.post("/related_photo/delete", this.selectedImages).then(res => {
        if (res.data.code === '200') {
          this.$message({
            type: 'success',
            message: '删除成功',
            center: true,
          })
        }
        setTimeout(() => location.reload(), 1000);
      })
      this.selectedImages.pop();
    },
    // 导入图片
    importImages() {
      // 导入逻辑
      this.uploadVisible = true
    },
    // 选择图片
    selectImage(image) {
      const index = this.selectedImages.indexOf(image);
      if (index === -1) {
        this.selectedImages.push(image);
      } else {
        this.selectedImages.splice(index, 1);
      }
    },
    // 全选/取消全选
    selectAll() {
      if (this.isAllSelected) {
        this.selectedImages = [];
      } else {
        this.selectedImages = this.images.slice();
      }
    },
    // 搜索图片
    searchImages() {
      // 使用 this.searchInput 进行搜索逻辑
    },
    // 图片是否已选
    isSelected(image) {
      return this.selectedImages.includes(image);
    },
    // 删除已选图片
    deleteSelected() {
      request.post("/related_photo/delete", this.selectedImages).then(res => {
        if (res.data.code === '200') {
          this.$message({
            type: "success",
            message: '删除成功',
            center: true,
          })
        }
        location.reload();
      })
    },
    // 下载已选图片
    downloadSelected() {
      // 下载已选图片逻辑
      this.selectedImages.forEach(url => {
        downloadFile(url.fileName, "photo")
      });
    }
  }
};
</script>

<style scoped>
.image-gallery {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.toolbar {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.left-section {
  display: flex;
}

.right-section {
  display: flex;
}

.image-card-container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.image-card {
  padding: 10px;
  border: 1px solid #ccc;
  transition: box-shadow 0.3s;
  cursor: pointer;
  margin-right: 10px;
  margin-bottom: 10px;
}

.image-card:hover {
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}

.image-wrapper {
  width: 100%;
  height: calc(100% - 30px);
}

.color-block {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.image {
  max-width: 100%;
  max-height: 100%;
}

.buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 3px;
  height: 30px;
}

.action-button {
  padding: 0;
  width: calc(33% - 1px);
}

.pagination-block {
  width: 100%;
  display: flex;
  justify-content: left;
  background-color: white;
  padding: 10px;
  z-index: 1000;
}
</style>
